import Vue from 'vue'
import VueRouter from 'vue-router'

// 1.2导入登录组件
// import Login from '../views/Login.vue'
import Login from '@/views/Login.vue'
import Home from '@/views/Home.vue'
import Welcome from '@/views/Welcome.vue'
import User from '@/views/User/User.vue'
import Rights from '@/views/Rights/Rights.vue'
import Roles from '@/views/Rights/Roles.vue'
import Cate from '@/views/Goods/Cate.vue'
import Params from '@/views/Goods/Params.vue'
import GoodList from '@/views/Goods/GoodList.vue'
import addGoods from '@/views/Goods/addGoods.vue'
import Order from '@/views/Order/Order.vue'
import Report from '@/views/Report'

Vue.use(VueRouter)

// 1.3配置路由规则
const routes = [
  // 1.4路由重定向
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/users',
        component: User
      },
      {
        path: '/rights',
        component: Rights
      },
      {
        path: '/roles',
        component: Roles
      },
      {
        path: '/categories',
        component: Cate
      },
      {
        path: '/params',
        component: Params
      },
      {
        path: '/goods',
        component: GoodList
      },
      {
        path: '/goods/addgood',
        component: addGoods
      },
      {
        path: '/orders',
        component: Order
      },
      {
        path: '/reports',
        component: Report
      }
    ]
  }

]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 如果是登录界面直接访问
  if (to.path === '/login') return next()
  const tokenStr = window.sessionStorage.getItem('token')
  // 没有携带token跳转的登录界面
  if (!tokenStr) return next('/login')
  // 存在token直接跳转
  next()
})

export default router
